package cn.zhejianglao.shirotemplate.config.web;

import cn.zhejianglao.shirotemplate.service.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * intercept request
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService IUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        try {
            IUserService.getCurrentUser();
            return true;
        } catch (Exception e) {
            OutputStream os = response.getOutputStream();
            os.write("user not logged in".getBytes());
            os.flush();
            os.close();
            return false;
        }
    }
}
